﻿using BL_Client.ServiceReference1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UI
{
    public partial class Students : System.Web.UI.Page
    {
        static BL_Client.IBL bl = new BL_Client.BL();
        static User user;

        public Students()
        {
            user = bl.GetUserByEmail(User.Identity.Name);
        }

        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (userIsAdmin(user)) //check the role of the user
                this.Page.MasterPageFile = "~/Admin.Master";
            else
                this.Page.MasterPageFile = "~/AvBait.Master";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var cities = bl.GetAllCities().ToList();
                cities.Insert(0, new City { ID = 0, Name = "All cities" });

                ddlCities.DataTextField = "Name";
                ddlCities.DataValueField = "ID";
                ddlCities.DataSource = cities;
                ddlCities.DataBind();
            }

            if (userIsAdmin(user))
                jTableScript.InnerHtml = @"<script type=""text/javascript"">
                                              $(document).ready(function () {
                                                $('#StudentsTableContainer').jtable({
                                                    title: 'Table of Students',
                                                    paging: true,
                                                    pageSize: 20,
                                                    sorting: true,
                                                    defaultSorting: 'FirstName ASC',
                                                    actions: {
                                                        listAction: '/Students.aspx/StudentListByFilter',
                                                        createAction: '/Students.aspx/CreateStudent',
                                                        updateAction: '/Students.aspx/UpdateStudent',
                                                        deleteAction: '/Students.aspx/DeleteStudent'
                                                        },
                                                        fields: {
                                                            ID: {
                                                                key: true,
                                                                list: false
                                                            },
                                                            FirstName: {
                                                                title: 'First Name',
                                                                width: '7%'
                                                            },
                                                            LastName: {
                                                                title: 'Last Name',
                                                                width: '7%'
                                                            },
                                                            PhoneNumber: {
                                                                title: 'Phone Number',
                                                                width: '10%',
                                                                sorting: false
                                                            },
                                                            Email: {
                                                                title: 'Email',
                                                                width: '15%',
                                                                sorting: false
                                                            },
                                                            CityID: {
                                                                title: 'City Name',
                                                                width: '10%',
                                                                options: '/Students.aspx/GetCitys'
                                                            },
                                                            ProgramID: {
                                                                title: 'Program Name',
                                                                width: '10%',
                                                                options: '/Students.aspx/GetPrograms'
                                                            },
                                                            ProfessionID: {
                                                                title: 'Profession Name',
                                                                width: '26%',
                                                                options: '/Students.aspx/GetProfessions'
                                                            },
                                                            Comments: {
                                                                title: 'Comments',
                                                                width: '15%',
                                                                type: 'textarea',
                                                                list: 'false',
                                                                sorting: false
                                                            }
                                                        },
                                                        formCreated: function (event, data) {
                                                                        data.form.find('input[name=""FirstName""]').addClass('validate[required]');
                                                                        data.form.find('input[name=""LastName""]').addClass('validate[required]');
                                                                        data.form.find('input[name=""PhoneNumber""]').addClass('validate[required,custom[phone]');
                                                                        data.form.find('input[name=""Email""]').addClass('validate[required,custom[email]');
                                                                        data.form.validationEngine();
                                                        },
                                                        formSubmitting: function (event, data) {
                                                            return data.form.validationEngine('validate');
                                                        },
                                                        formClosed: function (event, data) {
                                                            data.form.validationEngine('hide');
                                                            data.form.validationEngine('detach');
                                                        }
                                                    });

                                            $('#LoadRecordsButton').click(function (e) {
                                                e.preventDefault();
                                                $('#StudentsTableContainer').jtable('load', {
                                                    firstname: $('#lastname').val(),
                                                    lastname: $('#firstname').val(),
                                                    cityId: $('#" + ddlCities.ClientID + @"').val()
                                                });
                                            });

                                            $('#LoadRecordsButton').click();                                            
                                    });
                    </script>";
            else if (user.Role == Role.AvBait)
                jTableScript.InnerHtml = @"<script type=""text/javascript"">
                                              $(document).ready(function () {
                                                $('#StudentsTableContainer').jtable({
                                                    title: 'Table of Students',
                                                    paging: true,
                                                    pageSize: 20,
                                                    sorting: true,
                                                    defaultSorting: 'FirstName ASC',
                                                    actions: {
                                                        listAction: '/Students.aspx/StudentListByFilter'
                                                        },
                                                        fields: {
                                                            ID: {
                                                                key: true,
                                                                list: false
                                                            },
                                                            FirstName: {
                                                                title: 'First Name',
                                                                width: '7%'
                                                            },
                                                            LastName: {
                                                                title: 'Last Name',
                                                                width: '7%'
                                                            },
                                                            PhoneNumber: {
                                                                title: 'Phone Number',
                                                                width: '10%',
                                                                sorting: false
                                                            },
                                                            Email: {
                                                                title: 'Email',
                                                                width: '15%',
                                                                sorting: false
                                                            },
                                                            CityID: {
                                                                title: 'City Name',
                                                                width: '10%',
                                                                options: '/Students.aspx/GetCitys'
                                                            },
                                                            ProgramID: {
                                                                title: 'Program Name',
                                                                width: '10%',
                                                                options: '/Students.aspx/GetPrograms'
                                                            },
                                                            ProfessionID: {
                                                                title: 'Profession Name',
                                                                width: '26%',
                                                                options: '/Students.aspx/GetProfessions'
                                                            },
                                                            Comments: {
                                                                title: 'Comments',
                                                                width: '15%',
                                                                type: 'textarea',
                                                                list: 'false',
                                                                sorting: false
                                                            }
                                                        },
                                                        formCreated: function (event, data) {
                                                                        data.form.find('input[name=""FirstName""]').addClass('validate[required]');
                                                                        data.form.find('input[name=""LastName""]').addClass('validate[required]');
                                                                        data.form.find('input[name=""PhoneNumber""]').addClass('validate[required,custom[phone]');
                                                                        data.form.find('input[name=""Email""]').addClass('validate[required,custom[email]');
                                                                        data.form.validationEngine();
                                                        },
                                                        formSubmitting: function (event, data) {
                                                            return data.form.validationEngine('validate');
                                                        },
                                                        formClosed: function (event, data) {
                                                            data.form.validationEngine('hide');
                                                            data.form.validationEngine('detach');
                                                        }
                                                    });

                                            $('#LoadRecordsButton').click(function (e) {
                                                e.preventDefault();
                                                $('#StudentsTableContainer').jtable('load', {
                                                    firstname: $('#lastname').val(),
                                                    lastname: $('#firstname').val(),
                                                    cityId: $('#" + ddlCities.ClientID + @"').val()
                                                });
                                            });

                                            $('#LoadRecordsButton').click();                                            
                                    });
                    </script>";
        }

        [WebMethod(EnableSession = true)]
        public static object StudentsList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                //Get data from database
                int studentsCount = bl.GetAllStudents().Count();
                List<Student> students = bl.GetStudents(jtStartIndex, jtPageSize, jtSorting).ToList();

                //Return result to jTable
                return new { Result = "OK", Records = students, TotalRecordCount = studentsCount };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }

        }

        [WebMethod(EnableSession = true)]
        public static object StudentListByFilter(string firstname, string lastname, int cityId, int jtStartIndex, int jtPageSize, string jtSorting = null)
        {
            try
            {
                //Get data from database
                //int studentsCount = bl.GetAllStudents().Count();
                List<Student> students = bl.GetStudentsByFilter(firstname, lastname, cityId, jtStartIndex, jtPageSize, jtSorting).ToList();

                //Return result to jTable
                return new { Result = "OK", Records = students, TotalRecordCount = students.Count };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object CreateStudent(Student record)
        {
            if (!userIsAdmin(user))
                return new { Result = "ERROR" };

            try
            {
                if (bl.AddStudent(record))
                {
                    Student addedStudent = record;
                    return new { Result = "OK", Record = addedStudent };
                }
                else
                {
                    return new { Result = "ERROR", Message = "Student insertion error" };
                }
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }
        /*
         * 
         * */
        [WebMethod(EnableSession = true)]
        public static object UpdateStudent(Student record)
        {
            if (!userIsAdmin(user))
                return new { Result = "ERROR" };

            try
            {
                bl.UpdateStudent(record);
                return new { Result = "OK" };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object DeleteStudent(int ID)
        {
            if (!userIsAdmin(user))
                return new { Result = "ERROR" };

            try
            {
                bl.RemoveStudent(ID);
                return new { Result = "OK" };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object GetCitys()
        {
            try
            {
                var Citys = bl.GetAllCities().Select(d => new { DisplayText = d.Name, Value = d.ID }).OrderBy(d => d.DisplayText);
                return new { Result = "OK", Options = Citys };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }

        }

        [WebMethod(EnableSession = true)]
        public static object GetPrograms()
        {
            try
            {
                var Programs = bl.GetAllPrograms().Select(d => new { DisplayText = d.Name, Value = d.ID }).OrderBy(d => d.DisplayText);
                return new { Result = "OK", Options = Programs };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }


        }

        [WebMethod(EnableSession = true)]
        public static object GetProfessions()
        {
            try
            {
                var Professions = bl.GetAllProfessions().Select(d => new { DisplayText = d.Name, Value = d.ID }).OrderBy(d => d.DisplayText);
                return new { Result = "OK", Options = Professions };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        private static bool userIsAdmin(User user)
        {
            return (user.Role == Role.Admin);
        }
    }
}